"""
教学质量评估相关的数据模型
避免Pydantic版本兼容性问题，使用简单的数据类
"""
from datetime import datetime
from typing import List, Dict, Optional, Any, Tuple
from dataclasses import dataclass
from enum import Enum


class TeachingBehavior(str, Enum):
    """教学行为类型枚举"""
    LECTURING = "lecturing"
    WRITING_BOARD = "writing_board"
    DEMONSTRATING = "demonstrating"
    QUESTIONING = "questioning"
    ANSWERING = "answering"
    WALKING = "walking"
    GESTURING = "gesturing"
    INTERACTING = "interacting"
    OBSERVING = "observing"
    RESTING = "resting"


class TeachingStyle(str, Enum):
    """教学风格枚举"""
    AUTHORITATIVE = "authoritative"
    INTERACTIVE = "interactive"
    DEMONSTRATIVE = "demonstrative"
    COLLABORATIVE = "collaborative"
    INQUIRY_BASED = "inquiry_based"
    MIXED = "mixed"


class FatigueLevel(str, Enum):
    """疲劳度等级枚举"""
    VERY_LOW = "very_low"
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    VERY_HIGH = "very_high"


class InteractionQuality(str, Enum):
    """互动质量等级枚举"""
    EXCELLENT = "excellent"
    GOOD = "good"
    AVERAGE = "average"
    POOR = "poor"
    VERY_POOR = "very_poor"


@dataclass
class TeacherBehaviorAnalysisRequest:
    """教师行为分析请求"""
    classroom_id: str
    session_id: str
    teacher_detection: Dict[str, Any]
    image_data: str  # base64编码的图像数据
    audio_features: Optional[Dict[str, Any]] = None
    timestamp: Optional[datetime] = None


@dataclass
class TeacherBehaviorAnalysisResponse:
    """教师行为分析响应"""
    analysis_id: str
    teacher_id: str
    timestamp: datetime
    behavior: str
    gesture_data: Dict[str, Any]
    facial_expression: Dict[str, float]
    movement_data: Dict[str, Any]
    voice_features: Dict[str, float]
    fatigue_level: str
    confidence: float


@dataclass
class InteractionAnalysisRequest:
    """师生互动分析请求"""
    teacher_id: str
    classroom_id: str
    session_id: str
    student_attention_data: List[Dict[str, Any]]
    audio_features: Optional[Dict[str, Any]] = None
    timestamp: Optional[datetime] = None


@dataclass
class InteractionAnalysisResponse:
    """师生互动分析响应"""
    interaction_id: str
    teacher_id: str
    timestamp: datetime
    interaction_type: str
    duration: float
    student_response_count: int
    teacher_question_count: int
    interaction_quality: str
    engagement_score: float
    effectiveness_score: float


@dataclass
class TeachingStyleAnalysisRequest:
    """教学风格分析请求"""
    teacher_id: str
    analysis_period: Optional[int] = 30  # 分析天数


@dataclass
class TeachingStyleAnalysisResponse:
    """教学风格分析响应"""
    analysis_id: str
    teacher_id: str
    teaching_style: str
    style_confidence: float
    behavior_distribution: Dict[str, float]
    interaction_patterns: Dict[str, Any]
    strengths: List[str]
    improvement_areas: List[str]
    recommendations: List[str]


@dataclass
class TeachingQualityReportRequest:
    """教学质量报告请求"""
    teacher_id: str
    classroom_id: str
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class TeachingQualityReportResponse:
    """教学质量报告响应"""
    report_id: str
    teacher_id: str
    classroom_id: str
    analysis_period: Tuple[datetime, datetime]
    overall_score: float
    behavior_analysis: Dict[str, Any]
    interaction_analysis: Dict[str, Any]
    style_analysis: Dict[str, Any]
    fatigue_analysis: Dict[str, Any]
    improvement_suggestions: List[str]
    generated_at: datetime


@dataclass
class TeacherStatisticsRequest:
    """教师统计请求"""
    teacher_id: str
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class TeacherStatisticsResponse:
    """教师统计响应"""
    teacher_id: str
    time_range: Optional[Tuple[datetime, datetime]]
    total_observations: int
    total_interactions: int
    behavior_distribution: Dict[str, int]
    most_common_behavior: str
    fatigue_distribution: Dict[str, int]
    avg_fatigue_level: float
    avg_engagement_score: float
    avg_effectiveness_score: float


@dataclass
class TeachingComparisonRequest:
    """教学对比请求"""
    teacher_ids: List[str]
    comparison_metrics: List[str]  # behavior, interaction, style, fatigue
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class TeachingComparisonResponse:
    """教学对比响应"""
    comparison_id: str
    teacher_ids: List[str]
    comparison_period: Tuple[datetime, datetime]
    comparison_metrics: List[str]
    comparison_data: Dict[str, Dict[str, Any]]
    rankings: Dict[str, List[Dict[str, Any]]]
    insights: List[str]


@dataclass
class FatigueMonitoringRequest:
    """疲劳度监控请求"""
    teacher_id: str
    monitoring_period: str = "24h"  # 1h, 6h, 24h, 7d
    alert_threshold: str = "high"   # medium, high, very_high


@dataclass
class FatigueMonitoringResponse:
    """疲劳度监控响应"""
    teacher_id: str
    monitoring_period: str
    current_fatigue_level: str
    fatigue_trend: str
    alert_triggered: bool
    alert_message: Optional[str]
    recommendations: List[str]
    monitoring_data: List[Dict[str, Any]]


@dataclass
class TeachingEffectivenessRequest:
    """教学效果评估请求"""
    teacher_id: str
    classroom_id: str
    evaluation_criteria: List[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class TeachingEffectivenessResponse:
    """教学效果评估响应"""
    teacher_id: str
    classroom_id: str
    evaluation_period: Tuple[datetime, datetime]
    effectiveness_score: float
    effectiveness_grade: str
    contributing_factors: Dict[str, float]
    improvement_suggestions: List[str]
    benchmark_comparison: Dict[str, Any]


@dataclass
class InteractionQualityRequest:
    """互动质量评估请求"""
    teacher_id: str
    interaction_types: List[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class InteractionQualityResponse:
    """互动质量评估响应"""
    teacher_id: str
    evaluation_period: Tuple[datetime, datetime]
    overall_quality_score: float
    quality_by_type: Dict[str, float]
    interaction_patterns: Dict[str, Any]
    improvement_recommendations: List[str]


@dataclass
class TeachingDashboardRequest:
    """教学仪表板请求"""
    teacher_ids: List[str]
    time_range: str = "24h"  # 1h, 6h, 24h, 7d, 30d


@dataclass
class TeachingDashboardResponse:
    """教学仪表板响应"""
    dashboard_id: str
    teacher_ids: List[str]
    time_range: str
    summary_statistics: Dict[str, Any]
    behavior_trends: List[Dict[str, Any]]
    interaction_metrics: Dict[str, Any]
    fatigue_alerts: List[Dict[str, Any]]
    quality_rankings: List[Dict[str, Any]]
    recommendations: List[str]
    generated_at: datetime


# 辅助函数
def to_dict(obj) -> Dict[str, Any]:
    """将数据类转换为字典"""
    if hasattr(obj, '__dict__'):
        result = {}
        for key, value in obj.__dict__.items():
            if isinstance(value, datetime):
                result[key] = value.isoformat()
            elif isinstance(value, Enum):
                result[key] = value.value
            elif isinstance(value, (list, tuple)):
                result[key] = [to_dict(item) if hasattr(item, '__dict__') else item for item in value]
            elif isinstance(value, dict):
                result[key] = {k: to_dict(v) if hasattr(v, '__dict__') else v for k, v in value.items()}
            else:
                result[key] = value
        return result
    return obj


def from_dict(data_class, data: Dict[str, Any]):
    """从字典创建数据类实例"""
    if not hasattr(data_class, '__annotations__'):
        return data
    
    kwargs = {}
    for field_name, field_type in data_class.__annotations__.items():
        if field_name in data:
            value = data[field_name]
            
            # 处理datetime类型
            if field_type == datetime and isinstance(value, str):
                kwargs[field_name] = datetime.fromisoformat(value)
            # 处理Optional类型
            elif hasattr(field_type, '__origin__') and field_type.__origin__ is Union:
                kwargs[field_name] = value
            else:
                kwargs[field_name] = value
    
    return data_class(**kwargs)